package com.example.springboot.UserSerive;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.Mapper.SpUserMapper;
import com.example.springboot.common.Constants;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.pojo.InUser;
import com.example.springboot.pojo.SpUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService extends ServiceImpl<SpUserMapper,SpUser> {
    private  static final Log LOG=Log.get();
    public InUser login(InUser inUser) {
        QueryWrapper<SpUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",inUser.getUsername());
        queryWrapper.eq("password",inUser.getPassword());
        SpUser one;
        try {
            one=getOne(queryWrapper);
        }catch (Exception e){
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        if(one!=null){
            BeanUtil.copyProperties(one,inUser,true);
            return inUser;
        }
        else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }

    }

    public SpUser register(InUser inUser) {
        SpUser one=get(inUser);
        if(one==null){
            one=new SpUser();
            BeanUtil.copyProperties(inUser,one,true);
            save(one);
        }else {
            throw new ServiceException(Constants.CODE_600, "用户名存在");
        }
        return one;
    }

    private SpUser get(InUser inUser){
        QueryWrapper<SpUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",inUser.getUsername());
        queryWrapper.eq("password",inUser.getPassword());
        SpUser one;
        try {
            one=getOne(queryWrapper);
        }catch (Exception e){
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        return one;
    }



//    @Autowired
//    private SpUserMapper usermapper;
//
//    public int in(SpUser spUser){
//        if(spUser.getId()==null){
//           return usermapper.in(spUser);
//        }
//        //更新
//        else {
//        return  usermapper.update(spUser);
//        }
//    }

//    //plus-新增/更新
//    public boolean saveUser(SpUser spUser){
////        if(spUser.getId()==null){
////        return   save(spUser);
////        }else{
////           return updateById(spUser);
////        }
//      return saveOrUpdate(spUser);
//    }


}
